﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Crank.Core;
using System.IO;

namespace Crank
{
    class Program
    {

               private static string inFileName;
        private static string outFileName;

        private static void InitFileNames(string[] args)
        {
            switch (args.Length)
            {
                case 0: // Calc InFile and Calc OutFile
                    inFileName = "default.cal";
                    outFileName = inFileName + ".sql";
                    break;
                case 1: // Assume InFile Calc OutFile
                    inFileName = args[0];
                    outFileName = inFileName + ".sql";
                    break;
                case 2: // Assume InFile and OutFile
                    inFileName = args[0];
                    outFileName = args[1];
                    break;
                default: // Whoops
                    ShowUsage(Console.Error);
                    throw new ArgumentException("args");
            }
        }

        static void Main(string[] args)
        {
            TextWriter writer = null;
            try
            {
                Preprocessor.InstallDefaultDirectives();

            var model = new DataModel();

                InitFileNames(args);

                writer = new StreamWriter(outFileName, false);

                model.ParseFile( inFileName );
                model.ApplyTransform<StandardTransforms>();
                model.ScriptWith<Sql2005DropScripter>( writer );
                model.ScriptWith<Sql2005CreateScripter>( writer );
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                ShowUsage(Console.Error);
            }
            finally
            {
                if (writer != null)
                {
                    writer.Flush();
                    writer.Close();
                }
            }
        }

        private static void ShowUsage(TextWriter writer)
        {
            writer.WriteLine(@"USAGE:

  Crank.exe [sourcefile] [destinationfile]");
        }
    }
}
